﻿using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPITest.Models;
using WebAPITest.Models.Database;

namespace WebAPITest.service
{
    public class RedisService: IRedisService
    {
        

        private readonly IDatabase _redis;
        public RedisService(RedisHelper client)
        {
            //创建Redis连接对象
            _redis = client.GetDatabase();
            
        }
        /// <summary>
        /// 添加用户的浏览记录
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="good"></param>
        public void AddGoodViews(int userId,Good good)
        {
            var key = $"UserViews{userId}";

            var jsonStr = JsonConvert.SerializeObject(good);
            _redis.ListLeftPush(key, jsonStr);

        }
        /// <summary>
        /// 获取用户浏览记录
        /// </summary>
        public List<Good> GetUserViews(int userId)
        {
            var key = $"UserViews{userId}";
            var data = _redis.ListRange(key, 0, 4);
            var list = new List<Good>();
            foreach(var item in data)
            {
                var good = JsonConvert.DeserializeObject<Good>(item);
                list.Add(good);
            }
            
            return list;
        }
    }
}
